const router = require("koa-router")();
const path = require("path");
const fs = require("fs");
const md5 = require("md5");
router.get("/", async (ctx, next) => {
  await ctx.render("index", {
    title: "Hello Koa 2!"
  });
});

router.get("/string", async (ctx, next) => {
  ctx.body = "koa2 string";
});

router.get("/json", async (ctx, next) => {
  ctx.body = {
    title: "koa2 json"
  };
});

router.get("/updateUserInfo", async (ctx, next) => {
  console.log(ctx.session.temp);
  ctx.session.temp = null;
  console.log(ctx.session.temp);

  let username;
  console.log(ctx.session.username);
  console.log("sessionId:", ctx.sessionId);
  if (ctx.session.username) {
    username = ctx.session.username;
  } else {
    ctx.session.username = "Caroline22";
  }
  ctx.body = {
    loginData: {
      userName: username
    }
  };
});

// 接收文件上传文件
router.post("/upload", async (ctx, next) => {
  // 0. 获取请求参数
  const requestBody = ctx.request.body;
  const file = ctx.request.files.file;
  // 1. 接受传入文件
  if (ctx.session.temp) {
    ctx.session.temp.hash[requestBody.index] = file.path;
    ctx.session.temp.num = ctx.session.temp.num + 1;
  } else {
    ctx.session.temp = {
      name: requestBody.name,
      total: requestBody.total,
      num: 1,
      hash: {
        0: file.path
      }
    };
  }
  // 2. 文件传输完成，开始合并文件
  var reader, upStream;
  if (ctx.session.temp.num == ctx.session.temp.total) {
    for (let i = 0; i < ctx.session.temp.total; i++) {
      // 从缓存读取文件内容
      reader = fs.createReadStream(ctx.session.temp.hash[requestBody.index]);
      let filePath =
        path.join(__dirname, "../public/images/") + `${ctx.session.temp.name}`;
      upStream = fs.createWriteStream(filePath);
    }
    reader.pipe(upStream);
    console.log("文件上传成功");
    ctx.session.temp = "";
    return (ctx.body = {
      data: "上传成功！"
    });
  }
  console.log(
    "当前完成进度：" +
      (ctx.session.temp.num / ctx.session.temp.total) * 100 +
      "%"
  );
  return (ctx.body = {
    data:
      requestBody.hash +
      "传输完成，当前完成进度：" +
      (ctx.session.temp.num / ctx.session.temp.total) * 100 +
      "%"
  });
});

router.post("/post", async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin", "*");
  ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE");
  ctx.set(
    "Access-Control-Allow-Headers",
    "x-requested-with, accept, origin, content-type"
  );
  ctx.set("Content-Type", "application/json;charset=utf-8");
  ctx.body = {
    title: "post json"
  };
});

module.exports = router;
